<template>
  <div id="socialSecurityArchives">
    <div class="pageStatistics">
      <p class="companyName">
        <SubsidiarySelect @change="handleCompanyChange" />
      </p>
      <p class="dataItem"> <span>全部职员：</span>{{total.userTotalCount}} </p>
      <p class="dataItem"> <span>参保中：</span>{{total.insuredTotalCount}} </p>
      <p class="dataItem"> <span>待参保：</span>{{total.uninsuredTotalCount}}</p>
      <p class="dataItem"> <span>已停保：</span>{{total.stopInsuredTotalCount}}</p>
    </div>
    <div class="pageHead">
      <el-form ref="archivesParams" :model="archivesParams" class="archivesParams">
        <el-form-item>
          <!-- 多选 -->
          <MultipleDepartments ref="departmentsSelect" :subId="archivesParams.subId" />
        </el-form-item>
        <el-form-item>
          <el-input placeholder="人员、工号" v-model="archivesParams.keyWord" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isConfirmLoading" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item style="float: right;text-align: right; margin-right:0; margin-top:2px;">
          <div style="display:flex;">
            <el-button type="primary" @click="handleBatchAdd">批量增员</el-button>
            <el-button type="primary" :loading="isExportLoading" @click="handleExport">导出</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageMain">
      <div class="tableContent">
        <el-table :data="tableData" style="width: 100%;" height="100%" v-loading='tableLoading' size='medium' class="pageInnerTable" @selection-change="handleSelect">
          <el-table-column align="center" type="selection" :selectable="rowIsSelect" />
          <el-table-column align="left" prop="realName" label="姓名" />
          <el-table-column align="left" prop="jobNo" label="工号" />
          <el-table-column align="left" prop="departmentName" label="部门" />
          <el-table-column align="left" prop="postName" label="岗位" />
          <el-table-column align="left" prop="insuredStatusDesc" label="参保状态">
            <span slot-scope="scope">
              {{!scope.row.insuredStatusDesc?'未参保':scope.row.insuredStatusDesc}}
            </span>
          </el-table-column>
          <el-table-column align="left" prop="ssafName" label="参保方案" />
          <el-table-column align="left" prop="ssafCity" label="参保城市" />
          <el-table-column align="left" prop="ssafDate" label="参保月份">
            <template slot-scope="scope">
              <span>{{scope.row.ssafDate == '0-00'?'':scope.row.ssafDate }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="lastTime" label="最近调整时间" />
          <el-table-column align="left" label="操作" width="200">
            <template slot-scope="scope">
              <div class="btnList">
                <el-button type="text" @click="handleToDetails(scope.row)">
                  <el-image :src="require('@/assets/images/socialSecurity/details.svg')"></el-image>
                  <el-image :src="require('@/assets/images/socialSecurity/details_active.svg')"></el-image>
                </el-button>
                <el-button type="text" v-if="!scope.row.insuredStatusDesc||scope.row.insuredStatusDesc != '参保中'" @click="handleEditArchives(scope.row,2)">

                  <el-image :src="require('@/assets/images/socialSecurity/add.svg')"></el-image>
                  <el-image :src="require('@/assets/images/socialSecurity/add_active.svg')"></el-image>
                </el-button>
                <template v-else>
                   <!-- 取消调整 -->
                  <el-button v-if="scope.row.isIneffective" type="text" @click="handleRevoke(scope.row)">
                    <el-image :src="require('@/assets/images/socialSecurity/revokeChange.svg')"></el-image>
                    <el-image :src="require('@/assets/images/socialSecurity/revokeChange_active.svg')"></el-image>
                  </el-button>
                  <!-- 调整按钮 -->
                  <el-button v-else type="text" @click="handleEditArchives(scope.row,3)">
                    <el-image :src="require('@/assets/images/socialSecurity/edit.svg')"></el-image>
                    <el-image :src="require('@/assets/images/socialSecurity/edit_active.svg')"></el-image>
                  </el-button>
                  
                  <el-button type="text" @click="handleStopProtect(scope.row)">
                    <el-image :src="require('@/assets/images/socialSecurity/stop.svg')"></el-image>
                    <el-image :src="require('@/assets/images/socialSecurity/stop_active.svg')"></el-image>
                  </el-button>

                  <!-- 社保补缴 -->
                  <el-button type="text" @click="handleSupplementaryPay(scope.row)">
                    <el-image :src="require('@/assets/images/socialSecurity/supplementaryPay.svg')"></el-image>
                    <el-image :src="require('@/assets/images/socialSecurity/supplementaryPay_active.svg')"></el-image>
                  </el-button>

                 
                </template>
              </div>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination :small="true" background @size-change="(data) => handleSearchChange(data,'pageSize')" @current-change="(data) => handleSearchChange(data,'pageIndex')" :current-page="archivesParams.pageIndex" :page-sizes=[10,20,50] :page-size="archivesParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total.totalCount" class="pagingChild"></el-pagination>
    </div>
    <BatchIncreaseStaff :visible.sync="isShowBatchEdit" :list="batchList" @search="searchDataList" />
    <!-- 社保详情弹窗，pageStatus 为4 --》 社保补缴补缴 -->
    <InsuredDetailsDialog :pageStatus="4" :visible.sync="isShowSupplementaryPay" :activeData="activeData" :isAccount="false" @search="searchDataList()" />
  </div>
</template>
<script>
import InsuredDetailsDialog from "@/views/personnelRegulate/rewardManagement/socialSecurity/components/InsuredDetailsDialog.vue";
import BatchIncreaseStaff from "@/views/personnelRegulate/rewardManagement/socialSecurity/components/BatchIncreaseStaff.vue";
import SubsidiarySelect from "@/views/personnelRegulate/rewardManagement/components/SubsidiarySelect.vue";
import MultipleDepartments from "@/views/personnelRegulate/rewardManagement/components/MultipleDepartments.vue";
export default {
  name: 'socialSecurityArchives',
  components: {
    BatchIncreaseStaff,
    SubsidiarySelect,
    MultipleDepartments,
    InsuredDetailsDialog
  },
  data() {
    return {
      archivesParams: {
        subId: '',
        keyWord: '',
        pageIndex: 1,
        pageSize: 10,
      },
      activeDeptList: [],
      isConfirmLoading: false,
      isExportLoading: false,
      tableData: [],
      tableLoading: false,
      total: {
        totalCount: 0, // 总条数
        uninsuredTotalCount: 0, // 待参保
        insuredTotalCount: 0, // 参保中
        userTotalCount: 0, //全部职员
        stopInsuredTotalCount: 0 // 已停保
      },
      batchList: [], //批量操作列表
      isShowBatchEdit: false, //控制批量增员弹窗显示
      isShowSupplementaryPay: false, //控制补缴弹窗显示
      activeData: {},
    };
  },
  methods: {
    searchDataList() {
      let params = '';
      for (const key in this.archivesParams) {
        if (Object.hasOwnProperty.call(this.archivesParams, key)) {
          const element = this.archivesParams[key];
          if (element && `${element}`.length > 0) {
            if (params.length == 0) {
              params += `?${key}=${element}`;
            } else {
              params += `&${key}=${element}`;
            }

          }
        }
      }
      this.tableLoading = true;
      this.$api.socialSecurity
        .GetArchivePageList(params, this.activeDeptList)
        .then(res => {
          if(res.data.data === null) {
            this.total = {
              totalCount: 0, // 总条数
              uninsuredTotalCount: 0, // 待参保
              insuredTotalCount: 0, // 参保中
              userTotalCount: 0, //全部职员
              stopInsuredTotalCount: 0 // 已停保
            };
          }else {
            this.total.totalCount = res.data.totalCount;
            this.total.uninsuredTotalCount = res.data.uninsuredTotalCount;
            this.total.insuredTotalCount = res.data.insuredTotalCount;
            this.total.userTotalCount = res.data.userTotalCount;
            this.total.stopInsuredTotalCount = res.data.stopInsuredTotalCount;
            
          }
          if (!res.data.data) {
            this.$message.warning(res.data.message);
            this.tableData = [];
            return;
          }
         
          this.tableData = res.data.data.items;
          for (const key in this.total) {
            this.total[key] = res.data.data[key];
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    stopProtect(archiveId) {
      this.$api.socialSecurity
        .EditArchivesStatus({ archiveId })
        .then(res => {
          if (res.data.status == 200) {
            this.$message.success(res.data.message);
            this.searchDataList();
          } else {
            this.$message.warning(res.data.message);
          }
          // console.log(res);
        });
    },

    /**
     * @description 通过当前列参保状态判断他是否可被勾选
     */
    rowIsSelect(row, index) {
      if (row.insuredStatusDesc != "参保中") return true;
      return false;
    },

    /**
     * @description 取消调整
     */
    revokeChange(rowData) {
      const { id, userId } = rowData;
      const params = `?archiveId=${id}&userId=${userId}`;
      this.$api.socialSecurity
        .EditIneffective(params)
        .then(res => {
          this.$message.success(res.data.message);
          this.searchDataList();
        });
    },

    /**
     * @description 子公司下拉框值变化,进入页面后，先获取子公司id，在执行查询列表操作
     */
    handleCompanyChange(subId) {
      console.log('subId修改----执行查询', subId);
      this.archivesParams.subId = subId;
      this.searchDataList();
    },

    /**
     * @description 点击搜索按钮调用查询方法
     */
    handleSearch() {
      this.activeDeptList = this.$refs.departmentsSelect.getDepartments();

      this.archivesParams.pageIndex = 1;
      // console.log('已选部门', );
      this.searchDataList();
    },

    /**
     * @description 批量增员
     */
    handleBatchAdd() {
      if (this.batchList.length == 0) return this.$message.warning('请勾选需要增员的职员');
      this.isShowBatchEdit = true;
    },

    /**
     * @description 监听表格勾选
     */
    handleSelect(selection) {
      this.batchList = selection;
      console.log(this.batchList);
    },
    handleExport() {
      this.isExportLoading = true;
      // 导出所有数据
      this.$api.socialSecurity
        .SsafArchiveExport({ subId: this.archivesParams.subId })
        .then(res => {
          console.log(res);
          if (res.data.status == 200) {
            const a = document.createElement('a');
            a.setAttribute('href', res.data.data);
            a.setAttribute('download', '');
            a.click();
          } else {
            this.$message.warning(res.data.message);
          }
        })
        .finally(() => {
          this.isExportLoading = false;
        });
    },

    /**
     * @description 切换页面或页大小是触发
     * @param data 属性值
     * @param prop 属性名
     */
    handleSearchChange(data, prop) {
      this.archivesParams[prop] = data;
      this.searchDataList();
    },

    /**
     * @description 进入员工信息详情页
     */
    handleToDetails(data) {
      this.$router.push({
        name: 'insuredRecord',
        params: {
          data,
          pageStatus: 1
        }
      });
    },

    /**
     * @description 增员/编辑
     * @param data 列表项
     */
    handleEditArchives(data, pageStatus) {
      console.log('增员/编辑');
      this.$router.push({
        name: 'insuredDetails',
        params: {
          data,
          pageStatus
        }
      });
    },

    /**
     * @description 停保
     * @param data 待操作列表项
     */
    handleStopProtect(data) {
      console.log(data);
      this.$confirm('是否要停保当前人员', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.stopProtect(data.id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消停保操作'
        });
      });
    },

    /**
     * @description 补缴
     * 
     */
    handleSupplementaryPay(rowData) {
      this.activeData = rowData;
      this.isShowSupplementaryPay = true;
    },

    /**
     * @description 取消调整
     */
    handleRevoke(row) {
      console.log(row);
      // this.
      this.$confirm('是否取消调整?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.revokeChange(row);
      }).catch();
    }
  },

  activated() {
    if (this.archivesParams.subId?.length) {
      this.searchDataList();
    }
    // console.log(this.$route);
  }
};
</script>
<style lang="less" scoped>
@import url("../less/common.less");
#socialSecurityArchives {
  .pageStatistics {
    height: 40px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #dcdfe6;
    color: #666666;
    margin-bottom: 10px;
    .companyName {
      width: 200px;
      // min-width: 200px;
    }
    .dataItem {
      font-size: 12px;
      margin: 0 15px;
    }
  }
  .pageMain {
    height: calc(100% - 97px) !important;
  }
  .tableContent {
    padding: 0;
    :deep(.el-table) {
      .el-button {
        margin: 0;
      }
    }
  }
  .pagingChild {
    float: right;
    margin-right: 10px;
    margin-top: 5px;
    .el-pagination__total {
      line-height: 28px;
    }
  }
  .archivesParams {
    .el-form-item {
      float: left;
      // width: 180px;
      margin-right: 15px;
      .el-input {
        width: 100%;
      }
    }
  }
}
.btnList {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  :deep(.el-button) {
    padding-left: 0;
    padding-right: 18px;
    .el-image {
      width: 26px;
      height: 26px;
      &:last-child {
        display: none;
      }
    }
    &:hover {
      .el-image {
        &:first-child {
          display: none;
        }
        &:last-child {
          display: inline-block;
        }
      }
    }
  }
}
</style>